package io.codescience.aianaly.controller;

import io.codescience.aianaly.model.User;
import io.codescience.aianaly.repository.UserRepository;
import io.codescience.aianaly.utils.JwtUtil;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Optional;

@Controller
public class AuthController {
    private final UserRepository userRepository;
    private final JwtUtil jwtUtil;

    public AuthController(UserRepository userRepository, JwtUtil jwtUtil) {
        this.userRepository = userRepository;
        this.jwtUtil = jwtUtil;
    }

    @GetMapping("/login")
    public String showLoginForm() {
        return "login";
    }

    @PostMapping("/login")
    public String login(String email, String password, Model model, HttpServletResponse response) {
        Optional<User> userOptional = userRepository.findByEmailAndPassword(email, password);

        if (userOptional.isPresent()) {
            User user = userOptional.get();

            // 生成JWT token
            String token = jwtUtil.generateToken(user);

            // 设置JWT token到cookie
            Cookie cookie = new Cookie("jwtToken", token);
            cookie.setHttpOnly(true);
            cookie.setPath("/");
            cookie.setMaxAge(24 * 60 * 60); // 24小时
            response.addCookie(cookie);

            if(user.isAdmin()){
                return "redirect:/admin/interview_admin";
            }else {
                return "redirect:/interview";
            }
        } else {
            model.addAttribute("error", "邮箱或密码错误");
            return "login";
        }
    }

    @GetMapping("/register")
    public String showRegisterForm() {
        return "register";
    }

    @PostMapping("/register")
    public String register(String email, String password, Model model, HttpServletResponse response) {
        if (userRepository.existsByEmail(email)) {
            model.addAttribute("error", "该邮箱已被注册");
            return "register";
        }

        User newUser = new User(email, password);
        if (email != null && email.contains("@")) {
            newUser.setUsername(email.substring(0, email.indexOf("@")));
        }else {
            newUser.setUsername(email);
        }
        newUser.setAvatarUrl("/static/images/img_03.png");
        userRepository.save(newUser);

        // 生成JWT token并设置cookie
        String token = jwtUtil.generateToken(newUser);
        Cookie cookie = new Cookie("jwtToken", token);
        cookie.setHttpOnly(true);
        cookie.setPath("/");
        cookie.setMaxAge(24 * 60 * 60);
        response.addCookie(cookie);

        return "redirect:/login?registered=true";
    }

    @GetMapping("/logout")
    public String logout(HttpServletResponse response) {
        // 清除JWT token cookie
        Cookie cookie = new Cookie("jwtToken", null);
        cookie.setHttpOnly(true);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);

        return "redirect:/login";
    }
}